package cn.jesin.css.handler;

import cn.jesin.css.common.Flag;
import cn.jesin.css.vo.responseformat.Code;
import cn.jesin.css.vo.responseformat.Result;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 谷汉斌
 * @description 未认证访问处理
 * @createTime 2024/7/24 上午9:56
 */
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // 设置响应状态码
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        ServletOutputStream outputStream = response.getOutputStream();
        Result<Object> result = Result.builder()
                .flag(Flag.FAIL.isCode())
                .code(Code.SERVER_ERROR.getCode())
                .message("该请求已被拦截！").build();
        String s = JSON.toJSONString(result);
        outputStream.write(s.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}